package net.mingsoft.basic.util;

import org.springframework.stereotype.*;
import org.springframework.context.*;
import javax.servlet.http.*;
import org.springframework.web.context.request.*;
import javax.servlet.*;
import org.springframework.beans.*;

@Component
public class SpringUtil implements ApplicationContextAware
{
    private static ApplicationContext applicationContext;
    private static ThreadLocal<HttpServletRequest> requestThreadLocal;
    
    public static HttpServletRequest getRequest() {
        try {
            final HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            return request;
        }
        catch (Exception e) {
            return SpringUtil.requestThreadLocal.get();
        }
    }
    
    public static void setRequest(final HttpServletRequest request) {
        SpringUtil.requestThreadLocal.set(request);
    }
    
    @Deprecated
    public static Object getBean(final ServletContext sc, final String beanName) {
        return getApplicationContext().getBean(beanName);
    }
    
    public static Object getBean(final String beanName) {
        return getApplicationContext().getBean(beanName);
    }
    
    public static <T> T getBean(final Class<T> cls) {
        return (T)getApplicationContext().getBean((Class)cls);
    }
    
    public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
    }
    
    public static ApplicationContext getApplicationContext() {
        return SpringUtil.applicationContext;
    }
    
    static {
        SpringUtil.requestThreadLocal = new ThreadLocal<HttpServletRequest>();
    }
}
